package dao;

import java.util.ArrayList;
import java.util.List;

import models.Department;
import models.Employee;
import play.modules.objectify.Datastore;
import play.modules.objectify.ObjectifyService;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.Query;
import com.googlecode.objectify.helper.DAOBase;

public class EmployeeDao extends DAOBase {

	static {
		ObjectifyService.register(Employee.class);
	}

	public List<Employee> findAll() {
		Iterable<Employee> emps = Datastore.query(Employee.class).fetch();
		List<Employee> allEmps = new ArrayList<Employee>();
		for (Employee e : emps) {
			allEmps.add(e);
		}
		return allEmps;
	}

	public void save(Employee employee) {
		Datastore.put(employee);
	}
	
	public static Employee findById(Long id) {
		return Datastore.find(Employee.class, id, true);
	}

	public static void delete(Long id) {
		Employee employee = findById(id);
		Datastore.delete(employee);
	}

	public List<Employee> findAllDepartmentEmployees(Long id) {
		DepartmentDao departmentDao = new DepartmentDao();
		Objectify ofy = ObjectifyService.begin();
		Iterable<Employee> emps = ofy.query(Employee.class).filter("department", departmentDao.findById(id));
		List<Employee> allEmps = new ArrayList<Employee>();
		for (Employee e : emps) {
			allEmps.add(e);
		}
		return allEmps;
	}

	public void addEmployeesToDepartment(Long id) {
		DepartmentDao departmentDao = new DepartmentDao();
		List<Department> allDepartments = departmentDao.findAll();
		if(allDepartments.size() > 0) {
			Department department = allDepartments.get(0);
			Employee employee = findById(id);
			employee.setDepartment(new Key<Department>(Department.class, department.getId()));
			Datastore.put(employee);
		}
	}

}
